import React from 'react'
import { useAppSelector } from '../../store'
import ListItem from '../../components/listItem'
import { Radio, Stepper } from 'react-vant'
import { SubmitBar, Checkbox } from 'react-vant';
import { useDispatch } from 'react-redux';
import { addCar, changeAllState, changeState, subCar } from '../../store/car/carSlice';
import { useNavigate } from 'react-router-dom';
const Index: React.FC = () => {
  const carList = useAppSelector(state => state.car.carList)
  const dispatch = useDispatch()
  const totalState = carList.every(v => v.state)
  const totalPrice = carList.filter(v => v.state).reduce((p, n) => p + n.price * n.count, 0)
  const navigate = useNavigate()
  const onSubmit = () => {
    navigate('/order', {
      state: {
        title: '商品',
        price: totalPrice,
      }
    })
  }
  return (
    <div className='car'>
      {
        carList.map((v, i) => {
          return <ListItem
            key={i}
            v={v}
            desc={<Stepper
              value={v.count}
              onPlus={() => dispatch(addCar(v))}
              onMinus={() => dispatch(subCar(v))}
              min={1}
            ></Stepper>}
            preFix={<Checkbox checked={v.state} onChange={() => dispatch(changeState(v))}></Checkbox>}
          ></ListItem>
        })
      }

      <SubmitBar
        price={totalPrice * 100}
        buttonText="提交订单"
        onSubmit={onSubmit}
      >
        <Checkbox checked={totalState} onChange={() => dispatch(changeAllState(!totalState))}>全选</Checkbox>
      </SubmitBar>
    </div>
  )
}
export default Index